﻿using System;
using System.Text;
using System.Net.Sockets;
using System.Collections.Generic;

namespace LibMSNP.HTTP
{
    public class HTTPPacket
    {
        private HTTPPacketHeader _header;
        private string _body;

        public HTTPPacket(string body, HTTPPacketHeader header)
        {
            _header = header;
            _body = body;
        }

        /// <summary>
        /// Constructs an HTTPPacket from an array of bytes
        /// </summary>
        /// <param name="packet">HTTP Packet formatted as an array of bytes</param>
        public HTTPPacket(byte[] packet)
        {
            string pack = new string(ASCIIEncoding.ASCII.GetChars(packet));
            string[] parts = pack.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            string[] line = parts[0].Split(new char[] { ' ' });

            if (line[0] == "HTTP/1.1")
            {
                _header = new HTTPResponseHeader(line[1], line[2]);
            }
            else
            {
                _header = new HTTPRequestHeader(line[0], line[1]);
            }
            int index = 1;
            for (; index < parts.Length - 1; index++)
            {
                int colon = parts[index].IndexOf(':');
                string key = parts[index].Substring(0, colon);
                _header[key] = parts[index].Substring(colon + 2);
            }

            _body = parts[index].Trim(new char[] {'\0'});
        }

        public void SerializeToStream(System.IO.Stream stream, System.Text.Encoding enc)
        {
            string packet = _header.ToString() + _body;
            byte[] buffer = enc.GetBytes(packet);
            stream.Write(buffer, 0, buffer.Length);
            stream.Flush();
        }

        public HTTPPacketHeader Headers
        {
            get
            {
                return _header;
            }
            set { }
        }

        /// <summary>
        /// Turn a HTTPPacket into its string format
        /// </summary>
        /// <returns>Properly formatted HTTPPacket</returns>
        public override string ToString()
        {
            return _header.ToString() + _body;
        }

        public byte[] ToByteArray()
        {
            return ASCIIEncoding.ASCII.GetBytes(this.ToString());
        }

        /*internal HTTPPacket Copy()
        {
            HTTPPacketHeader header = new HTTPPacketHeader(this._header.Method, this._header.Resource);
            foreach (KeyValuePair<string, string> kvp in this.Headers.Headers)
            {
                header[kvp.Key] = kvp.Value;
            }

            return new HTTPPacket(this._body, header);
        }*/
    }
}